var app = getApp();
var ajax = require('../../utils/ajax.js');

Page({
  data: {
    dataLoaded: true,
    isCatHide: true,

    curTy: 0,
    curTyName: '',
    catList: [],
    goodsList: [],

    page: 1,
    loading: false,
    moreLoading: false,
    noMore: false,
  },


  onShareAppMessage: function () {
    return {
      title: this.data.shop.shareTitle,
      path: "pages/index/index"
    }
  },


  onLoad: function (options) {
    this.setData({
      curTy: options.ty
    });
    this._getList();
  },

  _switchCat(evt) {
    var catId = evt.target.dataset.catId;

    this.setData({
      curTy: catId,
      page: 1,
      isCatHide: true,
    });

    this._getList();
  },

  _getList(options) {
    var _self = this;
    var isMore = options && options.isMore;
    var page = _self.data.page || 1;

    if (isMore) {
      _self.setData({
        moreLoading: true
      });
    } else {
      _self.setData({
        loading: true
      });
    }

    ajax.G('/openapi/CHome/categoryPage', {
      catId: _self.data.curTy,
      page: _self.data.page
    }, function (data) {
      var goodsList = data.result.goodsList || [];
      var catList = data.result.catList || [];

      var toData = {
        goodsList: isMore ? _self.data.goodsList.concat(goodsList) : goodsList,
        catList,
        noMore: goodsList.length == 0,
        page: _self.data.page + 1,
        curTyName: data.result.title,
      };

      toData[isMore ? 'moreLoading' : 'loading'] = false;
      _self.setData(toData);
    });
  },

  /**
   * 加载更多
   */
  _loadMore: function () {
    if (this.data.moreLoading || this.data.loading || this.data.noMore) {
      return;
    }
    this._getList({
      isMore: true
    });
  },

  _showCat: function () {
    this.setData({
      isCatHide: !this.data.isCatHide
    });
  },

  _bodyTap(evt) {
    if (evt.target.dataset.tagName == 'curCat') {
      return;
    }
    this.setData({
      isCatHide: true
    });
  }


})